import { createRouter, createWebHistory } from 'vue-router'
import NotFound from '@/views/NotFound.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/404',
      name: 'not-found',
      component: NotFound,
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404',
    },
    {
      path: '/',
      name: 'login',
      component: Login,
    },
    {
      path: '/main',
      name: 'main',
      component: Main,
      redirect: '/main/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('@/components/good/Dashboard.vue')
        },
        {
          path: 'goods-list',
          name: 'goods-list',
          component: () => import('@/components/good/GoodList.vue')
        },
        {
          path: 'admin-list',
          name: 'admin-list',
          component: () => import('@/components/AdminList.vue')
        },
        {
          path: 'goods-category',
          name: 'goods-category',
          component: () => import('@/components/good/GoodCategory.vue')
        },
        {
          path: 'product-spec',
          name: 'product-spec',
          component: () => import('@/components/good/ProductSpec.vue')
        },
        {
          path: 'brand-management',
          name: 'brand-management',
          component: () => import('@/components/good/BrandManagement.vue')
        },
        {
          path: 'order-list',
          name: 'order-list',
          component: () => import('@/components/order/OrderList.vue')
        },
        {
          path: 'refund-handle',
          name: 'refund-handle',
          component: () => import('@/components/order/RefundHandle.vue')
        },
        {
          path: 'user-list',
          name: 'user-list',
          component: () => import('@/components/UserList.vue')
        },
      ],
    },
  ],
})

/**
 * 路由权限配置表
 * key: 路由名称, value: 允许访问的角色列表
 */
const routePermissions = {
  'dashboard': ['1', '2', '3'],           // 所有人都能访问（仪表盘）
  'goods-list': ['1', '2'],               // 超管和商品管理员
  'goods-category': ['1', '2'],           // 超管和商品管理员
  'product-spec': ['1', '2'],             // 超管和商品管理员
  'brand-management': ['1', '2'],         // 超管和商品管理员
  'order-list': ['1', '3'],               // 超管和数据分析员
  'refund-handle': ['1'],                 // 仅超级管理员
  'admin-list': ['1'],                    // 仅超级管理员
  'user-list': ['1'],                     // 仅超级管理员
};

// 路由守卫：验证 token 和权限
router.beforeEach(async (to, from, next) => {
  // 1. 允许访问登录页
  if (to.path === '/' || to.path === '/login') {
    next();
    return;
  }

  // 2. 检查 token 是否存在
  const token = localStorage.getItem('token');
  if (!token) {
    // 没有 token，重定向到登录页
    next('/');
    return;
  }

  // 3. 恢复用户信息到 Store
  const { useUserStore } = await import('@/store/index.js');
  const userStore = useUserStore();

  if (!userStore.isLoggedIn) {
    const restored = userStore.restoreUserInfo();
    if (!restored) {
      // 恢复失败，数据被篡改，强制重新登录
      const { ElMessage } = await import('element-plus');
      ElMessage.error('登录信息已过期或被篡改，请重新登录');
      next('/');
      return;
    }
  }

  // 4. 检查路由权限
  const routeName = to.name;
  if (routePermissions[routeName]) {
    const allowedRoles = routePermissions[routeName];
    if (!allowedRoles.includes(userStore.role)) {
      // 没有权限访问该路由
      const { ElMessage } = await import('element-plus');
      ElMessage.error(`您没有权限访问该页面 (当前角色: ${userStore.role})`);
      // 重定向到仪表盘
      next('/main/dashboard');
      return;
    }
  }

  // 5. 通过所有检查，允许访问
  next();
});

export default router